import os
import re

from lxml import etree

from pyframe.exceptions.document_file_not_found_exception import DocumentFileNotFoundException

class Helper:

	def __init__(self):
		pass

	def createDocumentFromFile(self, fileName):

		if(not(os.path.isfile(fileName))):
			raise DocumentFileNotFoundException(fileName)

		return etree.parse(fileName)

	def createDocumentFromFileForIterParse(self, fileName, events = ("end", "pi")):

		if(not(os.path.isfile(fileName))):
			raise DocumentFileNotFoundException(fileName)

		tree = etree.iterparse(fileName, events)

		return tree

	def serializeNode(self, node):

		return etree.tostring(node)

	def createNodeFromString(self, xml):

		return etree.XML(xml)

	def replaceNodeByString(self, node, xml):

		if(not xml):
			return node.getparent().remove(node)

 		node.getparent().replace(node, etree.XML(xml))

	def replaceChildrenByString(self, node, xml):

		for child in node.getchildren():
			node.remove(child)

		if(xml):
			node.append(etree.XML(xml))

	def getTemplateFileNameFromDocument(self, document):

		node = document.getroot().getprevious()

		while not node is None:
			if(node.target == 'xsl-stylesheet'):
				return re.search(r'href="(.+)"', node.text).group(1)
			node = node.getprevious()

	def processXSLT(self, document, templateFileName):

		template = etree.parse(templateFileName)
		output = template.xpath('xsl:output/@method', namespaces = {'xsl' : 'http://www.w3.org/1999/XSL/Transform'})

		return { 'output' : output[0] if len(output) > 0 else 'html', 'document' : document.xslt(template) }